package com.gk.carshopsys.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gk.carshopsys.pojo.CarOrderImport;
import com.gk.carshopsys.pojo.PartOrderImport;
import com.gk.carshopsys.service.CarOrderService;
import com.gk.carshopsys.service.PartOrderService;
import org.springframework.util.CollectionUtils;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;


public class PartOrderDataListener extends AnalysisEventListener<PartOrderImport> {

    private PartOrderService partorderService;

    public PartOrderDataListener(PartOrderService partorderService) {
        this.partorderService = partorderService;
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<PartOrderImport> list = new ArrayList<PartOrderImport>();

    @Override
    public void invoke(PartOrderImport data, AnalysisContext context) {
        System.out.println("解析到一条数据:{}"+data.toString());

        String now = new Date(System.currentTimeMillis()).toString();
        data.setCreate_time(now);
        data.setUpdate_time(now);

        Date date = new Date(System.currentTimeMillis());

//获取年月日
        java.text.SimpleDateFormat sformat = new java.text.SimpleDateFormat();
        sformat.applyPattern("yyyy");
        String year = sformat.format(date);
        sformat.applyPattern("MM");
        String mouth = sformat.format(date);
        sformat.applyPattern("dd");
        String day = sformat.format(date);

//        生成3位随机数
        int randow=(int)(Math.random()*(900+100));
        String ordernum =  year+mouth+day+data.getPartid()+data.getPartid()+data.getCustid()+randow;

        data.setOrdernum(ordernum);



        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        System.out.println("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        System.out.println("{}条数据，开始存储数据库！"+list.size());
        if (!CollectionUtils.isEmpty(list)) {
            partorderService.addPartOrderByList(list);
        }
        System.out.println("存储数据库成功！");
    }

}
